<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use fast\Http;

use think\cache\driver\Redis;
/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("tpyeList", $this->model->getTpyeList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // var_dump($where);exit();

            $list = $this->model
                ->with(['user','company','pay','grouporder'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $ke=>$row) {

                $row->getRelation('user')->visible(['nickname','recommend']);
                $row->getRelation('company')->visible(['name']);

                $row->getRelation('pay')->visible(['name','status']);

                
                
                
                $row->top_nickname = model('app\common\model\User')->where('id',$row['user']['recommend'])->value('nickname');


               
            }


            $money = $this->model
                ->with(['user','company','pay'])
                ->where($where)
                ->where('tpye','in','1,3')
                ->where('order.status','in',['2','3','4'])
                ->sum('pay_total');

            $money_2 = $this->model
                ->with(['user','company','pay'])
                ->where($where)
                ->where('tpye',2)
                ->where('order.status','in',['2','3','4'])
                ->sum('pay_total');
            // $money = 0;

            $total=$list->total();
            $rows=$list->items();
            foreach ($rows as $k=>$row) {
                if ($row['tpye']==2){
                    if (!empty($row['grouporder'])){
                        if ($row['user_id']==$row['grouporder']['user_id']){
                        }else{
                            unset($list[$ke]);
                        }
                    }
                }
            }

            $result = array("total" => $total, "rows" =>$rows ,'money'=>$money,'money2'=>$money_2);

            // $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);





        if ($params['status'] == 3) {
            $params['deliverytime'] = time();


        }


        // if ($params['status'] > 1 && $params['status'] < 5 && $row['status'] == 1) {

        //     // $params['paytime'] = time();
        //     if($params['status'] == 2 && !$row['paytime']){

        //         $params['paytime'] = time();

        //     }

        //     if($params['status'] == 3 ){

        //     }


        // }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 详情
     */
    public function detail($ids = null)
    {

        $row = $this->model
            ->with(['user','company','ordergoods','pay','grouporder'])
            ->where('order.id',$ids)
            ->find();

// 		var_dump($row);exit();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['tpye']==2){
            if (!empty($row['grouporder'])){
                if ($row['user_id']==$row['grouporder']['user_id']){
                    $order=$this->model->with(['ordergoods'])
                        ->where('grouporder_id',$row['grouporder_id'])
                        ->select();
                    if (!empty($order)){
                        foreach ($order as $k=>$v){
                            foreach ($v['ordergoods'] as $k1=>$v1){
                                $row['ordergoods'][]=$v1;
                            }
                        }
                    }
                }
            }
        }
//        $this->error($row);
        $row['address'] = model('app\common\model\order\Address')->where('order_id',$ids)->find();
// 		print_r("<pre>");print_r($row);exit();
// 		$row['patient'] = model('app\common\model\Patient')
// 			->where(['order_id' => $ids])
// 			->find();

// 		$row['User'] = model('app\common\model\User')
// 			->where(['id' => $row['user_id']])
// 			->find();
// 		$row['ordergoods'] =  DB::name('order_goods')->where('order_id',$ids)->select();
// 		$row['courier'] =  DB::name('user')->where('id',$row['courier_id'])->find();
// 		var_dump($row);exit();

// 		$row['pay'] = model('app\admin\model\wanlshop\Pay')
// 			->where(['order_id' => $row['id'], 'type' => 'goods'])
// 			->find();

// 		// 查询快递状态
// 		switch ($row['state']) {
// 			case 1:
// 				$express = [
// 					'context' => '付款后，即可将宝贝发出',
// 					'status' => '尚未付款',
// 					'time' => date('Y-m-d H:i:s', $row['createtime'])
// 				];
// 				break;
// 			case 2:
// 				$express = [
// 					'context' => '商家正在处理订单',
// 					'status' => '已付款',
// 					'time' => date('Y-m-d H:i:s', $row['paymenttime'])
// 				];
// 				break;
// 			default: // 获取物流
// 				$eData = model('app\api\model\wanlshop\KuaidiSub')
// 					->where(['express_no' => $row['express_no']])
// 					->find();
// 				// 获取数据 兼容PHP7.4	1.1.5升级
// 				if(!empty($eData['data'])){
// 					$ybData = json_decode($eData['data'], true);
// 					// 运单状态 1.0.6升级
// 					$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
// 					$status = $statusText[0];
// 					if(in_array('status', $ybData[0])){
// 						$status = $ybData[0]['status'];
// 					}else{
// 						if($eData['ischeck'] === 1){
// 							$status = $statusText[3];
// 						}else{
// 							$status = $statusText[$eData['state']];
// 						}
// 					}
// 					$express = [
// 						'status' => $status,
// 						'context' => $ybData[0]['context'],
// 						'time' => $ybData[0]['time'],
// 					];
// 				}else{
// 					$express = [
// 						'status' => '已发货',
// 						'context' => '包裹正在等待快递小哥揽收~',
// 						'time' => date('Y-m-d H:i:s', $row['delivertime'])
// 					];
// 				}
// 		}
// 		$this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function change($ids){
        $status = $this->request->request('status');

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if($row['status'] != 6){
            $this->error(__('已被审核'));
        }

        $row->is_examine = $status;

        if($status == 2){
            // model('app\common\model\Order')->backOrder($row['order_sn']);
            $row->status = 2;
            $row->save();
            $this->success('订单支付成功');
        }else{
            $row->is_examine = 3;
            $row->status = 7;
            $row->save();
            $this->success('拒绝成功');

        }


    }
    
    public function setOrderStatus($ids){
        
        
        $status = $this->request->request('status');

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $excode = 'sahnde';
        
        $openid = model('app\common\model\User')->where('id',$row['user_id'])->value('openid');
        
        $goodsName =  model('app\common\model\order\Goods')->where('order_id',$ids)->value('goods_name');
        
        // ,$row,$goodsName,$openid
        
        $Redis = new Redis();
        
        $key = 'access_token';
        
    	$access_token = $Redis->get($key); 
    	
    	
    	
    	if (!$access_token) {
    	    
    		$config = get_addon_config('epay');
    		
    		$appId = $config['wechat']['miniapp_id'];
    		
    		$appSecret = $config['wechat']['app_secret'];
    		
    // 		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
    		
    		$params = [
                'appid' => $config['wechat']['miniapp_id'],
                'secret' => $config['wechat']['app_secret'],
     
            ];
    		
    		$res = Http::sendRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential", $params, 'GET');
    		
    	    $access_token = json_decode($res['msg'],1);
    		
    		$access_token = $access_token['access_token'];
    		
  
    		if ($access_token) {
    		    
    			$Redis->set($key,$access_token,7100);
    		} 
    	}
    	
    	
    	   $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token='. $access_token;
		    $datas = '{
                "order_key": {
                    "order_number_type": 2,
                    "transaction_id": "'.$row['transaction_id'].'"
                },
                    "delivery_mode": 1,
                    "logistics_type": 4,
                    "shipping_list": [
                        {
                            "tracking_no": "'.'SN'.time().rand(1000,9999).'",
                            "express_company": "'.$excode.'",
                            "item_desc": "'.$goodsName.'",
                            "contact": {
                                "consignor_contact": "177****1234"
                            }
                        }
                    ],
                    "upload_time": "'.date(DATE_RFC3339).'"'.',
                    "payer": {
                        "openid": "'.$openid.'"
                    }
                }
            ';
      
    	 $request  = $this->https_request($url, $datas);
    	 
    	 $request = json_decode($request, true);
    	 
    	 if($request['errmsg'] == 'ok'){
    	     $row->send_goods = 1;
    	     $row->taketime = time();
    	     $row->save();
    	     $this->success('success');
    	 }else{
    	      $this->error($request['errmsg']);
    	 }
    	 
    	 
    
    	 
    // 	 send_goods
    	
    // 	var_dump( $access_token);

    }
    
    public function https_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

//线下核销
    public function xianxiahexiao($ids)
    {
        $data=$this->request->request(['ids'=>$ids]);
//        $data=json_decode($data,true);
        $order=$this->model
            ->where('status',2)
            ->where('company_id','<>',8)
            ->where('id',$data['ids'])
            ->find();
        if (!empty($order)){
            $order->company_id=8;
            $order->status=3;
            $order->save();
            $this->success('成功!');
        }
//        return false;
        $this->error("失败!");
    }

}
